package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/1/4.
 */
public class UnfinishInfoActivity extends BaseActivity implements View.OnClickListener {
    //数据库
    private DBManager db = null;
    private ImageView report, status;
    private TextView tv;
    private Button sure;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog dialog;
    private String id;
    AlphaAnimation appearAnimation;
    ScrollView scrollView;
    MyGridView gridview;
    //保存异常数据
    private ArrayList<HashMap<String, String>> array = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unfinishinfo);
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();

        initView();
    }

    private void initView() {
        appearAnimation = new AlphaAnimation(0, 1);
        appearAnimation.setFillAfter(true);
        appearAnimation.setDuration(200);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        TextView title_name = (TextView) findViewById(R.id.title_name);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        report = (ImageView) findViewById(R.id.activity_unfinishinfo_iv1);
        status = (ImageView) findViewById(R.id.activity_unfinishinfo_iv2);
        gridview = (MyGridView) findViewById(R.id.gridview);
        tv = (TextView) findViewById(R.id.activity_unfinishinfo_tv);
        sure = (Button) findViewById(R.id.activity_unfinishinfo_sure);
        if (getIntent().getStringExtra("ProcessStatus").equals("0")) {
            title_name.setText("解读中");
        } else if (getIntent().getStringExtra("ProcessStatus").equals("1")) {
            title_name.setText("已解读");
        } else {
            title_name.setText("识别失败");
        }

        img_back.setOnClickListener(this);
        sure.setOnClickListener(this);
        id=getIntent().getStringExtra("id");
        if (NetworkUtil.isNetworkAvailable(UnfinishInfoActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(UnfinishInfoActivity.this, R.layout.dialog_loading);
            SheetInfo(id);
        } else {
            ToastUtil.showToast(UnfinishInfoActivity.this, R.string.no_network_hint);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.activity_unfinishinfo_sure:
                if (id != null) {
                    dialog = new MyAlertDialog().ShowDialog(UnfinishInfoActivity.this, R.layout.dialog_loading);
                    putSheet(id);
                }
                break;
        }
    }

    private void putSheet(final String id) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("reportId", id);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.FinishSure).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        handler2.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        handler2.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
             if(dialog!=null){
                 dialog.dismiss();
             }
            switch (msg.what) {
                case 0:
                    Intent cameraintent = new Intent(UnfinishInfoActivity.this, ReadHistoryActivity.class);
                    cameraintent.putExtra("data", "1");
                    startActivity(cameraintent);
                    finish();
                    break;
                case 1:
                    ToastUtil.showToast(UnfinishInfoActivity.this, "确认失败");
                    break;
            }
        }
    };


    private void SheetInfo(final String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.SheetInfo(id)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    ToastUtil.showToast(UnfinishInfoActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonData(String bobys) {
        try {
            JSONObject jsonObject = new JSONObject(bobys);
            final String reportUrl = jsonObject.optString("reportUrl");
            if (jsonObject.optString("results") != null && !jsonObject.optString("results").equals("null") && !jsonObject.optString("results").equals("")) {
                JSONArray items = jsonObject.getJSONArray("results");
                if (items.length() > 0) {
                    array = new ArrayList<>();
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject object = items.getJSONObject(i);
                        int status = object.optInt("status");
                        if (status != 0) {
                            String chineseName = object.optString("chineseName");
                            String statusDescription = object.optString("statusDescription");
                            HashMap<String, String> map = new HashMap<>();
                            map.put("chineseName", chineseName);
                            map.put("statusDescription", statusDescription);
                            array.add(map);
                        }
                    }
                    gridview.setAdapter(new listAdpter(UnfinishInfoActivity.this, array));
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    imageLoader.displayImage(reportUrl, report, options, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {
                            //开始加载的时候执行
                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            //加载失败的时候执行
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            if (getIntent().getStringExtra("ProcessStatus").equals("0")) {
                                status.setImageResource(R.mipmap.fenxi);
                                tv.setText("报告分析中，请稍后进入解读历史查看");
                            } else {
                                if (array!=null&&array.size() > 0) {
                                    status.setVisibility(ImageView.GONE);
                                    tv.setVisibility(View.GONE);
                                    sure.setVisibility(View.VISIBLE);
                                    gridview.setVisibility(View.VISIBLE);
                                } else {
                                    status.setImageResource(R.mipmap.weiyichang);
                                    tv.setText("未发现异常指标");
                                    sure.setVisibility(View.VISIBLE);
                                }

                            }
                            scrollView.startAnimation(appearAnimation);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            //加载成功的时候执行
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            if (getIntent().getStringExtra("ProcessStatus").equals("0")) {
                                status.setImageResource(R.mipmap.fenxi);
                                tv.setText("报告分析中，请稍后进入解读历史查看");
                            } else if (getIntent().getStringExtra("ProcessStatus").equals("1")) {
                                if (array!=null&&array.size() > 0) {
                                    status.setVisibility(ImageView.GONE);
                                    tv.setVisibility(View.GONE);
                                    sure.setVisibility(View.VISIBLE);
                                    gridview.setVisibility(View.VISIBLE);
                                } else {
                                    status.setImageResource(R.mipmap.weiyichang);
                                    tv.setText("未发现异常指标");
                                    sure.setVisibility(View.VISIBLE);
                                }
                            } else if (getIntent().getStringExtra("ProcessStatus").equals("2")) {
                                status.setImageResource(R.mipmap.weiyichang);
                                tv.setText("识别出错");
                                sure.setVisibility(View.VISIBLE);
                            }
                            scrollView.startAnimation(appearAnimation);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {
                            //加载取消的时候执行
                        }

                        public void onProgressUpdate(String imageUri, View view, int current, int total) {
                            //进度条加载
                        }
                    });

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 适配器
     */
    public class listAdpter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private ArrayList<HashMap<String, String>> data = new ArrayList();


        public listAdpter(Context context, ArrayList<HashMap<String, String>> data) {
            this.context = context;
            this.data = data;
            inflater = LayoutInflater.from(context);
        }

        public void getData(ArrayList<HashMap<String, String>> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            ViewHolder holder = null;
            if (view == null) {
                holder = new ViewHolder();
                view = inflater.inflate(R.layout.unfinish_info_item, null);
                holder.name = (TextView) view.findViewById(R.id.name);
                holder.type = (TextView) view.findViewById(R.id.type);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.name.setText(data.get(position).get("chineseName"));
            holder.type.setText(data.get(position).get("statusDescription"));
            return view;
        }
    }

    class ViewHolder {
        private TextView name;
        private TextView type;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
